package com.niiwoo.civet.trade.service.local.newRefund.notify.mq;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectBorrowerPlanNew;
import com.niiwoo.civet.trade.dao.entity.RefundOrder;
import com.niiwoo.civet.trade.dao.entity.RefundOrderDetailBiz;
import com.niiwoo.civet.trade.dao.mapper.ProjectBorrowerPlanNewMapperExt;
import com.niiwoo.civet.trade.dto.FollowWorkTaskRepaymentDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.enums.RefundNotifyEnum;

@Component
public class ShengDunRefundResultNotify extends MQRefundNotify {

	@Autowired
	private ProjectBorrowerPlanNewMapperExt projectBorrowerPlanNewMapperExt;
	
	@Override
	public Object bulidParam(RefundNotifyDTO refundNotifyDTO) {
		Project project = refundNotifyDTO.getProject();
		RefundOrder refundOrder = refundNotifyDTO.getRefundOrder();
		
		// 查询此次还款的当前期数，即本次还款最小的期数
		Integer currentPeriod = getRepaymentCurrentPeriod(refundNotifyDTO);
		if (null == currentPeriod) {
			return null;
		}
		
		// 查询还款计划
		ProjectBorrowerPlanNew projectBorrowerPlanNew = projectBorrowerPlanNewMapperExt.selectByProjectAndPeriod(project.getProjectId(), currentPeriod);
		
		FollowWorkTaskRepaymentDTO followWorkTaskRepaymentDTO = new FollowWorkTaskRepaymentDTO();
		followWorkTaskRepaymentDTO.setBorrowerPlanId(projectBorrowerPlanNew.getId());
		followWorkTaskRepaymentDTO.setProjectId(projectBorrowerPlanNew.getProjectId());
		followWorkTaskRepaymentDTO.setOverState(projectBorrowerPlanNew.getStatus());
		followWorkTaskRepaymentDTO.setRepaymentAmount(refundOrder.getAmount());
		followWorkTaskRepaymentDTO.setProjectState(project.getStatus());
		followWorkTaskRepaymentDTO.setRepaymentDate(new Date());
        
        return followWorkTaskRepaymentDTO;
	}
	
	/**
	 * 获取本次还款的当前期数，即本次还款最小期限
	 * 
	 * @param refundNotifyDTO
	 * @return
	 */
	private Integer getRepaymentCurrentPeriod(RefundNotifyDTO refundNotifyDTO) {
		if (CollectionUtils.isEmpty(refundNotifyDTO.getRefundOrderDetailBizList())) return null;
		
		Integer currentPeriod = null;
		List<RefundOrderDetailBiz> refundOrderDetailBizList = refundNotifyDTO.getRefundOrderDetailBizList();
		for (RefundOrderDetailBiz refundOrderDetailBiz : refundOrderDetailBizList) {
			if (refundOrderDetailBiz.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
				continue;
			}
			if (currentPeriod == null || currentPeriod > refundOrderDetailBiz.getCurrentPeriod()) {
				currentPeriod = refundOrderDetailBiz.getCurrentPeriod();
			}
		}
		return currentPeriod;
	}

	@Override
	public RefundNotifyEnum getType() {
		return RefundNotifyEnum.SHENDUN_REFUND_RESULT;
	}
}